package cn.sylinx.horm.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class RelaxedPropertyResolver {

    private final Properties properties;
    private final String prefix;
    private final Map<String, Object> kv = new HashMap<>();

    public RelaxedPropertyResolver(Properties properties, String prefix) {
        this.properties = properties;
        this.prefix = prefix;
        init();
    }

    private void init() {
        Set<Object> keySets = properties.keySet();
        if (!keySets.isEmpty()) {
            for (Object key : keySets) {
                if (key.toString().startsWith(prefix)) {
                    kv.put(key.toString(), properties.get(key));
                }
            }
        }
    }

    public String getProperty(String key) {
        return getProperty(key, null);
    }

    public String getProperty(String key, String defaultValue) {
        String realKey = prefix + key;
        Object value = kv.get(realKey);
        if (value == null) {
            return defaultValue;
        }
        return value.toString();
    }

    public Map<String, Object> toMap() {
        Map<String, Object> kv = new HashMap<String, Object>();
        this.kv.forEach((k, v) -> {
            int len = prefix.endsWith(".") ? prefix.length() : prefix.length() + 1;
            String truelyKey = k.substring(len);
            kv.put(truelyKey, v);
        });
        return kv;
    }

    public Map<String, Object> getSubProperties(String keyPrefix) {
        String fullPrefix = prefix + keyPrefix;
        Map<String, Object> kvtmp = new HashMap<String, Object>();
        Set<Object> keySets = properties.keySet();
        if (!keySets.isEmpty()) {
            for (Object key : keySets) {
                if (key.toString().startsWith(fullPrefix)) {
                    String shotKey = key.toString().replaceFirst(fullPrefix, "");
                    kvtmp.put(shotKey, properties.get(key));
                }
            }
        }
        return kvtmp;
    }
}